package com.data.service.extension;

import com.data.model.constant.SqlParamConstant;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component(value = "MysqlDataSourceExtension")
public class MysqlDataSourceExtension implements DataSourceExtension {
    @Resource
    private DatasourceFactory datasourceFactory;

    @Override
    public String generateTableInfoSql(String databaseName, String tableName) {
        return String.format("select * from columns where table_schema ='%s' and table_name = '%s';", databaseName, tableName);
    }

    @SneakyThrows
    @Override
    public List<Map<String, Object>> execute(Datasource datasource, Map<String, String> params) {
        String sql = params.get(SqlParamConstant.SQL);

        DataSource dataSource = datasourceFactory.getDataSource(datasource.getBeanName());

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            List<Map<String, Object>> rows = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, Object> row = new HashMap<>();
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(metaData.getColumnName(i), resultSet.getObject(i));
                }
                rows.add(row);
            }
            return rows;
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
